#include "AHT20.h"
#include "mf_i2c.h"
#include "log.h"

const static char *TAG = "aht20.c";

FL_ErrorStatus aht20_init(void)
{
    bool ret = FL_PASS;
    uint8_t status;
    uint8_t init_cmd[2] = {0x08, 0x00};

    ret |= mf_i2c_master_read_from_device(AHT20_ADDRRES, 0x71, I2C_REG_BYTE_ADDR, &status, 1);
#if AHT20_DEBUG
    MY_LOGI(TAG, "status->%X [ret:%d]\r\n", status, ret);
#endif

    while ((status & 0x08) == 0) /* check status[3] is 1 ? */
    {
        ret |= mf_i2c_master_read_from_device(AHT20_ADDRRES, 0xBE, I2C_REG_BYTE_ADDR, init_cmd, 2);
        ret |= mf_i2c_master_read_from_device(AHT20_ADDRRES, 0x71, I2C_REG_BYTE_ADDR, &status, 1);
#if AHT20_DEBUG
        MY_LOGI(TAG, "status->%X[ret:%d]\r\n", status, ret);
#endif
    }

    MY_LOGI(TAG, "init succeffully. status[7:3]=[%#X]\r\n", status);

    return ret;
}

FL_ErrorStatus aht20_read_from_device(aht20_data *aht_param)
{
    bool ret = FL_PASS;
    uint8_t status;
    uint8_t init_cmd[2] = {0x33, 0x00};
    uint8_t buff_read[6];
    uint32_t raw_data_H, raw_data_T;

    ret |= mf_i2c_master_write_to_device(AHT20_ADDRRES, 0xAC, I2C_REG_BYTE_ADDR, init_cmd, 2);
    FL_DelayMs(75);
    ret |= mf_i2c_master_read_from_device(AHT20_ADDRRES, 0x71, I2C_REG_BYTE_ADDR, buff_read, 6);
    /* handle aht20 data start */
    if ((buff_read[0] & 0x08) == 0x08)
    {
#if 0
        MY_LOGI_DMA(TAG, "rd_data->%X-%X-%X-%X-%X-%X [ret:%d]\r\n", buff_read[0], buff_read[1], buff_read[2], buff_read[3], buff_read[4], buff_read[5], ret);
#endif
        raw_data_H = buff_read[1];
        raw_data_H = raw_data_H << 8;
        raw_data_H += buff_read[2];
        raw_data_H = raw_data_H << 8;
        raw_data_H += buff_read[3];
        raw_data_H = raw_data_H >> 4;

        raw_data_T = buff_read[3] & 0x0F;
        raw_data_T = raw_data_T << 8;
        raw_data_T += buff_read[4];
        raw_data_T = raw_data_T << 8;
        raw_data_T += buff_read[5];

        aht_param->humidity = (float)raw_data_H * 100 / 1048576;
        aht_param->temperature = (float)raw_data_T * 200 / 1048576 - 50;
#if AHT20_DEBUG
        MY_LOGI(TAG, "data->%.2fC %.2f%%\r\n", aht_param->temperature, aht_param->humidity);
#endif
    }
    /* handle aht20 data end */

    return ret;
}
